<template>
    <div class="project-approval-add">
        <ft-dialog :visible.sync="dialogVisible" width="600px" title="项目立项发起" height="297px" @close="onCancel">
            <el-form ref="dataRef" class="project-approval-add_form" :model='entityData'
                     size='small' inline :rules="rules" v-loading="loading">
                <el-row>
                    <el-col>
                        <ft-form-item label='客户名称' prop='customerId'>
                            <ft-customer ref="ftCustomer" v-model='entityData.customerId' @change="onChange"/>
                        </ft-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <ft-form-item label='证件号码:' prop='identityNo'>
                            <ft-input v-model='entityData.identityNo' :disabled="true"></ft-input>
                        </ft-form-item>
                    </el-col>
                </el-row>
              <el-row>
                <el-col>
                  <ft-form-item label='项目金额:' prop='projectApprovalAmt'>
                    <ft-number-input-unit v-model='entityData.projectApprovalAmt'
                                          :percentUtil="true"
                                          companyUnit="元"
                                          :precision='[14,2]'>
                    </ft-number-input-unit>
                  </ft-form-item>
                </el-col>
              </el-row>
                <el-row>
                    <el-col>
                        <ft-form-item label='租赁类型' prop='productMinEm'>
                          <el-select v-model="entityData.productMinEm" :editing='true' @change="onProduct" :multiple="false" clearable
                                     size="small">
                            <el-option v-for="item in dataProduct"
                                       :key="item.productMinEm"
                                       :label="item.productName"
                                       :value="item.productMinEm">
                            </el-option>
                          </el-select>
                        </ft-form-item>

                    </el-col>
                </el-row>
              <el-row>
                <el-col>
                  <ft-form-item label='所属组织' prop='belongOrgId'>
                    <el-select v-model="entityData.belongOrgId" :editing='true' @change="onBelongOrg" :multiple="false" clearable
                                 size="small">
                      <el-option v-for="item in dataBelongOrg"
                                 :key="item.orgId"
                                 :label="item.orgName"
                                 :value="item.orgId">
                      </el-option>
                    </el-select>
                  </ft-form-item>

                </el-col>
              </el-row>
              <el-row>
                <el-col >
                  <ft-form-item label='合同年份' prop='occupyYear'>
                    <el-date-picker
                        v-model="entityData.occupyYear"
                        type="years"
                        :picker-options="pickerOptions"
                        placeholder="选择年">
                    </el-date-picker>
                  </ft-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col v-if='isCurrentShow'>
                  <ft-form-item label='当年合同数量'  prop='currentOccupyNum' :required="this.isCEdit">
                    <el-input-number  @change="handleChange"  :max="10" v-model="entityData.currentOccupyNum"></el-input-number>
                  </ft-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col v-if='isNextShow'>
                  <ft-form-item label='次年合同数量'  prop='nextOccupyNum' :required="this.isNEdit">
                    <el-input-number  @change="handleChange"  :max="10" v-model="entityData.nextOccupyNum"></el-input-number>
                  </ft-form-item>
                </el-col>
              </el-row>
                <hr>
                <div class="form-floor_buttons">
                    <el-button size="small" @click="onCancel" :disabled="loading">取消</el-button>
                    <el-button class="save-button" type="primary" size="small" :disabled="loading" @click="beforeSave">保存
                    </el-button>
                </div>
            </el-form>
        </ft-dialog>
    </div>
</template>

<script>
import FtCustomer from "./ft/FtCustomer";

export default {
    name: "ProjectApprovalAdd",
    components: {FtCustomer},

    data() {
        return {
          isNextShow:false,
          isCurrentShow:true,
          dialogVisible: false,
          loading: false,
          dataProduct: [],
          isNEdit:false,
          isCEdit:true,
          dataBelongOrg: [],
          entityData: {
            currentOccupyNum:1,
            nextOccupyNum:1,
            occupyYear:[new Date().getTime(),]
          },
          rules: {
              occupyYear: [{required:true, message: '合同年份不能为空', trigger: ['blur']}],
              customerId: [{required: true, message: '客户名称不能为空', trigger: ['blur']}],
              projectApprovalAmt: [{required: true, message: '项目金额不能为空', trigger: ['blur']}],
              productMinEm: [{required: true, message: '租赁类型不能为空', trigger: ['blur']}],
              belongOrgId: [{required: true, message: '所属组织不能为空', trigger: ['blur']}],
          },
          pickerOptions: {
              disabledDate(time) {
                const currentYear = new Date().getFullYear();
                const nextYear = currentYear + 1;
                const year = time.getFullYear();
                return year < currentYear || year > nextYear;
              }
            }
          }
        },

  mounted() {
    this.requestProduct()
    this.requestOrg()
  },
  watch: {
    "entityData.occupyYear":function(val){
      var occupyYear = this.entityData.occupyYear;
      const currentYear = new Date().getFullYear();
      const nextYear = currentYear + 1;
      debugger
      if(occupyYear.toString().split(",").length > 1){
        this.isCurrentShow = true
        this.isNextShow = true
        this.isNEdit = true
        this.isCEdit = true
        this.$set(this.entityData,"currentOccupyNum",1);
        this.$set(this.entityData,"nextOccupyNum",1);
      }else{
        occupyYear.forEach(item=>{
          const time = new Date(item).getFullYear();
          if(time == currentYear){
            this.isCurrentShow = true
            this.isCEdit = true
            this.isNextShow = false
            this.isNEdit = false
            this.$set(this.entityData,"currentOccupyNum",1);
            this.$set(this.entityData,"nextOccupyNum",null);
          }else if(time == nextYear){
            this.isCurrentShow = false
            this.isNextShow = true
            this.isNEdit = true
            this.isCEdit = false
            this.$set(this.entityData,"currentOccupyNum",null);
            this.$set(this.entityData,"nextOccupyNum",1);
          }
        })
      }
    },
  },

    methods: {
      onShowCancel(){
        this.dialogVisible = true
      },
        handleChange(value) {
          console.log(value);
        },
        // 取消或返回
        onCancel() {
            this.$refs.dataRef.clearValidate()
            this.$refs['ftCustomer'].crearData();
            this.dialogVisible = false
            this.entityData = {
              currentOccupyNum:1,
              nextOccupyNum:1,
              occupyYear:[new Date().getTime(),]
            }
        },
      requestProduct() {
        if (true) {
          this.$http.get('/joys-rest/ncls-bms/approval/product/list').then(resp => {
            this.dataProduct = resp.body
          }, resp => {
            this.$message.error(resp.body.message)
          })
        }
      },
      requestOrg() {
          this.$http.get('/joys-rest/ncls-bms/approval/org/list/').then(resp => {
            this.dataBelongOrg = resp.body
          }, resp => {
            this.$message.error(resp.body.message)
          })
      },


        onChange(val) {
            this.$set(this.entityData, 'customerId', val.customerId);
            this.$set(this.entityData, 'customerName', val.customerName);
            this.$set(this.entityData, 'identityNo', val.identityNo);
            this.$set(this.entityData, 'customerInitId', val.initId);
            this.$refs.dataRef.clearValidate('customerId')
        },
        onProduct(item) {
            this.$set(this.entityData, 'productMainEm', item);
            this.$refs.dataRef.clearValidate('productMinEm')
        },
      onBelongOrg(item) {
          debugger
        this.$set(this.entityData, 'belongOrgId', item);
        this.$refs.dataRef.clearValidate('belongOrgId')
      },
      beforeSave: function () {
        // 防止重复操作
        if (this.loading) {
          return
        }
        this.$refs.dataRef.validate(validate => {
          if (validate) {
            let url = "/joys-rest/ncls-bms/approval/beforeSave/" + this.entityData.customerInitId
            this.$http.get(url).then(resp => {
              if (resp.bodyText) {
                let tip = ""
                if ("CUSTOMER_RATING" == resp.bodyText) {
                  tip = "暂无有效的评级等级，请及时完善"
                } else if ("AREA_LIMIT" == resp.bodyText) {
                  tip = "暂无有效的最终限额，请及时完善"
                }
                this.$message.info(tip)
                // this.$confirm(tip, '提示', {
                //   confirmButtonText: '确定',
                //   dangerouslyUseHTMLString: true,
                //   type: 'warning'
                // }).then(() => {
                this.onSave()
                this.onCancel()
                // })
              } else {
                this.onSave()
                this.onCancel()
              }
            }, resp => {
              this.$message.error("客户评级信息查询失败！")
            })
          }
        })

      },
        // 保存
        onSave() {
            // 防止重复操作
            if (this.loading) {
                return
            }
            this.$refs.dataRef.validate(validate => {
                if (validate) {
                    console.log(this.entityData,"---------------2");
                    console.log(this.entityData.occupyYear,"---------------1")
                    var fullYear = new Date().getFullYear();
                    let times = [];
                    this.entityData.occupyYear.forEach(date => {
                      let year = new Date(date).getFullYear();
                      times.push(year);
                    });
                    console.log(times,"---------------1")
                    if (this.entityData.occupyYear == null) {
                      this.entityData.occupyYear = fullYear.toString();
                    }else{
                      this.entityData.occupyYear = times.toString()
                    }
                    console.log(this.entityData,"---------------2");
                    this.loading = true
                    let url = "/joys-rest/ncls-bms/approval/save"
                    this.entityData.ifCircularLease = 'N'
                    this.$http.post(url, this.entityData).then(resp => {
                        let projectApprovalId = resp.body.projectApprovalId
                        if (projectApprovalId) {
                            this.onCancel();
                            this.$emit("onSuccess", projectApprovalId)
                        } else {
                            this.$message.error("新增失败！")
                        }
                    }, resp => {
                        if (resp.body) {
                            this.$message.error(resp.body.message || "新增失败！");
                            this.$refs.dataRef.clearValidate()
                        } else {
                            this.$message.error("新增失败！")
                        }
                    }).finally(() => {
                        this.loading = false
                    })
                }
            })
        },
    }
}
</script>

<style lang="less" scope>
.el-select-dropdown{
        max-width:392px !important;
    }
    .el-select-dropdown__item{
      overflow: visible;
    }
.project-approval-add {
    background-color: #FFFFFF;

    
    .project-approval-add_return {
        margin: 12px 24px;
    }

    hr {
        border: none;
        height: 1px;
        margin: 0;
        background-color: rgba(179, 179, 179, 0.20);
    }

    .project-approval-add_form {
        //margin: 24px 24px 0;
        padding-top: 24px;
        padding-right: 24px;
        background-color: #F1F7FD;

        hr {
            border: none;
            height: 1px;
            margin: 24px 0 0;
            background-color: rgba(179, 179, 179, 0.20);
        }

        .form-floor_buttons {
            width: 100%;
            height: 62px;
            display: flex;
            align-items: center;
            justify-content: flex-end;

            .save-button {
                margin-left: 16px;
                margin-right: 30px;
            }

        }
    }
}
</style>